<?php

/**
 * @author Martin Pernica
 * @copyright 2008
 */

class com_user_messages
{

    public static $max = 15;

    public static function getAll()
    {
        $query = Registry::get('db')->query("SELECT * FROM {prefix}users_messages WHERE `to` = '".User::getUid()."' ORDER BY date DESC");
        if ($query->num_rows != 0) {
            echo "<table>";
            echo "<tr><th></th><th>".Lang::getFront('com_user', 'messages_sender')."</th><th>".Lang::getFront('com_user', 'messages_date')."</th><th>".Lang::getFront('com_user', 'messages_subject')."</th><th></th></tr>";
            while ($data = $query->fetch_array()) {
                echo "<tr><td>" . self::messageStatus($data['status']) . "</td><td>" . User::
                    getDisplayName($data['sender']) . "</td><td>" . $data['date'] . "</td><td>" . $data['subject'] .
                    "</td><td><a href=\"{url}index.php?q=user/messages/view/".$data['id']."\"><img src=\"{url}libs/icons/email_open.png\" alt=\"open\" /> ".Lang::getFront('com_user', 'messages_open')."</a> <a href=\"{url}index.php?q=user/messages/delete/".$data['id']."\"><img src=\"{url}libs/icons/email_delete.png\" alt=\"delete\" /> ".Lang::getFront('com_user', 'messages_delete')."</a></td></tr>";
            }
            echo "</table>";
        } else {
            echo Lang::getFront('com_user', 'messages_emptybox');
        }

    }

    public static function send()
    {
        $subject = DbModel::escape(strip_tags($_POST['message_subject']));
        $text = DbModel::escape(htmlentities($_POST['message_text']));
        $status = 0;
        $sender = User::getUid();
        $to = intval($_POST['message_to']);

        if (self::check($to)) {
            $insert = Registry::get('db')->query("INSERT INTO {prefix}users_messages (`to`, `sender`, `status`, `subject`, `text`, `date`) VALUES ('" .
                $to . "', '" . $sender . "', '" . $status . "', '" . $subject . "', '" . $text .
                "', NOW())");
            echo Text::p(Lang::getFront('com_user', 'messages_success'));
            
            echo "\n<meta http-equiv=\"refresh\" content=\"3;url={url}index.php?q=user/messages/\">";
            
        } else {
            echo Text::p(Lang::getFront('com_user', 'messages_full'));
        }
    }

    public static function openSingle($id)
    {
        if (self::isOwner($id)) {

            $query = Registry::get('db')->query("SELECT * FROM {prefix}users_messages WHERE id = '" .
                intval($id) . "'");
            $data = $query->fetch_array();

            if ($data['status'] == 0) {
                $status = Registry::get('db')->query("UPDATE {prefix}users_messages SET status = '1' WHERE id = '" .
                    intval($id) . "'");
            }

            echo "<table>";
            echo "<tr><td><img src=\"{url}libs/icons/user.png\" alt=\"" .
                Lang::getFront('com_user', 'messages_sender') . "\" /> " . Lang::getFront('com_user', 'messages_sender') . " :</td><td><a href=\"{url}index.php?q=user/single/" .
                $data['sender'] . "\">" . User::getDisplayName($data['sender']) .
                "</a></td></tr>";
            echo "<tr><td><img src=\"{url}libs/icons/page_white_text_width.png\" alt=\"" .
                Lang::getFront('com_user', 'messages_subject') . "\" /> " . Lang::getFront('com_user', 'messages_subject') . " :</td><td>" . $data['subject'] .
                "</td></tr>";
            echo "<tr><td><img src=\"{url}libs/icons/date.png\" alt=\"" . Lang::getFront('com_user', 'messages_date') .
                "\" /> " . Lang::getFront('com_user', 'messages_date') . " :</td><td>" . $data['date'] . "</td></tr>";
            echo "<tr><td><br /></td></tr>";
            echo "<tr><td>" . stripslashes($data['text']) . "</td></tr>";
            echo "</table>";


        } else {
            echo Text::p(Lang::getFront('com_user', 'messages_notowner'));
        }
    }
    
    public static function delete($id)
    {
        if (self::isOwner($id)) {
            
            Registry::get('db')->query("DELETE FROM {prefix}users_messages WHERE id = '" .
            intval($id) . "'");
            
            echo Text::p(Lang::getFront('com_user', 'messages_deleted'));
            
            echo "\n<meta http-equiv=\"refresh\" content=\"3;url={url}index.php?q=user/messages/\">";
            
        } else {
            echo Text::p(Lang::getFront('com_user', 'messages_notowner'));
        }
    }

    private static function isOwner($id)
    {
        $to = Registry::get('db')->query("SELECT `to` FROM {prefix}users_messages WHERE id = '" .
            intval($id) . "'");
        $to = $to->fetch_array();

        if ($to['to'] != User::getUid()) {
            return false;
        } else {
            return true;
        }
    }

    private static function check($id)
    {
        $query = Registry::get('db')->query("SELECT COUNT(id) AS result FROM {prefix}users_messages WHERE `to` = '" .
            User::getUid() . "'");
        $i = $query->fetch_array();

        if ($i['result'] < intval(self::$max)) {
            return true;
        } else {
            return false;
        }
    }

    public static function messageStatus($int)
    {
        switch ($int) {
            case 1:
                return Lang::getFront('com_user', 'messages_true');
                break;

            case 0:
                return Lang::getFront('com_user', 'messages_true');
                break;
        }
    }

    public static function getUsers()
    {
        $users = Registry::get('db')->query("SELECT id, display_name FROM {prefix}users WHERE id != '".User::getUid()."' ORDER BY display_name");
        while ($d = $users->fetch_assoc()) {
            $users_final[$d['display_name']] = $d['id'];
        }
        return $users_final;
    }
    
    public static function panel()
    {
        Text::p('<a href="{url}index.php?q=user/messages/send"><img src="{url}libs/icons/pencil.png" alt="new" /> '.Lang::getFront('com_user', 'messages_new').'</a> &nbsp;&nbsp;&nbsp;<a href="{url}index.php?q=user/messages"><img src="{url}libs/icons/application_view_list.png" alt="list" /> '.Lang::getFront('com_user', 'messages_open').'</a>');
        Text::br();
    }

}

if (User::isLogged()) {

    switch ($q[2]) {
        case 'view':
        
            com_user_messages::panel();

            com_user_messages::openSingle($q[3]);

            break;
            
        case 'delete':
        
            com_user_messages::panel();

            com_user_messages::delete($q[3]);

            break;

        case 'send':
        
            com_user_messages::panel();

            $form = new Form;
            $form->addElement('select', array('name' => 'message_to', 'label' =>
                Lang::getFront('com_user', 'messages_recipient'), 'selected' => intval($_GET['to'])), com_user_messages::getUsers());
            $form->addTextbox('message_subject', Lang::getFront('com_user', 'messages_subject'))->notEmpty(Lang::getFront('com_user', 'messages_subject_empty'));
            $form->addTextarea('message_text', '', 15, 60)->notEmpty(Lang::getFront('com_user', 'messages_text_empty'));
            $form->addSubmit('message_submit', Lang::getFrontGlobal('submit'));
                
            $form->render();

            if ($form->isSubmitted()) {
                if($form->isValid()){
                    com_user_messages::send();
                }
            }

            break;

        default:
        
        	com_user_messages::panel();

            com_user_messages::getAll();

            break;
    }

}

?>